/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.healthcloud.utils;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 *
 * @author yucailong
 */
public class EncryptionUtils {
    
    

    /**
     * hexChar
     */
    public static char[] hexChar = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

    private static int bufferSize = 1024;


    public void setBufferSize(int bufferSize) {
        EncryptionUtils.bufferSize = bufferSize;
    }
    
    
    
    /**
     * 对FILE文件内容进行MD5加密
     *
     * @param fileName 文件名称
     * @return
     * @throws java.io.FileNotFoundException
     */
    public static String encryptionFileMd5(String fileName)
            throws IOException{
        InputStream fis = null;
        try {
            fis = new FileInputStream(fileName);
            byte[] buffer = new byte[bufferSize];
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            int numRead = 0;
            while ((numRead = fis.read(buffer)) > 0) {
                md5.update(buffer, 0, numRead);
            }
            return toHexString(md5.digest());
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        } finally {
            if(fis != null){
                fis.close();
            }
        }

    }

    /**
     * 对字符串进行md5加密
     *
     * @param str 字符串
     * @return
     */
    public static String encryptionMd5(String str) {
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
            md5.update(str.getBytes("utf-8"));

        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        } catch (UnsupportedEncodingException ex) {
            throw new RuntimeException(ex);

        }

        return toHexString(md5.digest());
    }

    /**
     * 16进制处理
     *
     * @param b byte[] 数组
     * @return
     */
    private static String toHexString(byte[] b) {
        StringBuilder sb = new StringBuilder(b.length * 2);

        for (byte by : b) {
            sb.append(hexChar[(by & 0xf0) >>> 4]);
            sb.append(hexChar[by & 0x0f]);
        }
        return sb.toString();
    }
}
